package cn.jbt.api.admin.util;

import cn.jbt.config.XxlJobConfig;
import com.alibaba.fastjson2.JSONObject;
import groovy.util.logging.Slf4j;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Data
@Accessors(chain = true)
@Slf4j
public class XxlJobUtil {

    private XxlJobConfig xxlJobConfig;

    public List<String> getCookiesByLogin() {

        RestTemplate restTemplate = new RestTemplate();
        // headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // form variables
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userName", xxlJobConfig.getUsername());
        map.add("password", xxlJobConfig.getPassword());
        // request
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        // response
        ResponseEntity<String> response = restTemplate.postForEntity(
                String.format("%s/login", xxlJobConfig.getAdminAddresses()),
                request, String.class);
        if (!response.getStatusCode().equals(HttpStatus.OK)) {
            throw new RuntimeException("请求错误：" + response.getStatusCode());
        }

        JSONObject result = JSONObject.parseObject(response.getBody());
        assert result != null;

        if (result.getInteger("code") != 200) {
            throw new RuntimeException(result.getString("msg"));
        }

        return response.getHeaders().get("Set-Cookie");
    }

}
